package com.kevin.es.test;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;

/**
 * @author kevin
 * 范围查询
 */
public class EStest_Doc_Query_Range {

    public static void main(String[] args) throws Exception {

        // 创建es客户端
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );

        /*// 查询数据
        SearchRequest request = new SearchRequest();
        request.indices("user");

        // 构建查询条件（全部查询）
        SearchSourceBuilder builder = new SearchSourceBuilder();
        // 构建范围查询器
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age");
        rangeQueryBuilder.lte(100);
        rangeQueryBuilder.gte(20);

        builder.query(rangeQueryBuilder);*/

        /**
         * 模糊查询
         */
        /*SearchRequest request = new SearchRequest();
        request.indices("user");

        // 构建查询条件（全部查询）
        SearchSourceBuilder builder = new SearchSourceBuilder();
        // 构建模糊查询器
        FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("name", "张三")
                // 匹配的时候允许相差一个字符
                .fuzziness(Fuzziness.ONE);
        builder.query(fuzzyQueryBuilder);*/
        /**
         * 高亮查询
         */
        SearchRequest request = new SearchRequest();
        request.indices("user");

        // 构建查询条件（全部查询）
        SearchSourceBuilder builder = new SearchSourceBuilder();
        // 构建查询器
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "张三");

        // 构建高亮显示构造器
        HighlightBuilder highlightBuilder = builder.highlighter();
        // 增加前缀
        highlightBuilder.preTags("<font color = 'red'>");
        // 增加后缀标签
        highlightBuilder.postTags("</font>");
        // 高亮显示的字段
        highlightBuilder.field("name");
        builder.query(termQueryBuilder);


        // 添加查询资源
        request.source(builder);

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();
        System.out.println(hits.getTotalHits());
        System.out.println(response.getTook());

        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsString());
        }
        // 关闭es客户端
        client.close();
    }
}
